<template>
  <div class="live-detail-container">
    <div class="live-content">
      <!-- 左侧直播播放器区域 -->
      <div class="live-player-container">
        <div class="video-container">
          <video
              class="video-js"
              ref="videoPlayer"
              muted
              playsinline
              style="background-color:rgb(18,9,37);width: 100%;height: 100%;"
          ></video>
        </div>
        <div class="live-info">
          <h2 class="live-title">{{ liveDetail.title || '直播标题' }}</h2>
          <div class="live-meta">
            <span class="live-views">
              <i class="el-icon-view"></i> {{ liveDetail.view_count || '0' }}人观看
            </span>
            <span class="live-time">
              <i class="el-icon-clock"></i> {{ liveDetail.createTime || '直播未开始' }}
            </span>
          </div>
        </div>
      </div>

      <!-- 右侧商品展示区域 -->
      <div class="live-products">
        <div class="products-header">
          <h3>直播商品</h3>
          <el-button type="primary" size="small" @click="refreshProducts">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </div>

        <el-scrollbar class="products-scroll">
          <div class="product-list">
            <div v-for="product in products" :key="product.id" class="product-item">
              <div class="product-image">
                <el-image
                    :src="product.image"
                    fit="cover"
                    :preview-src-list="[product.image]"
                ></el-image>
              </div>
              <div class="product-info">
                <h4 class="product-name">{{ product.name }}</h4>
                <p class="product-desc">{{ product.description }}</p>
                <div class="product-footer">
                  <span class="product-price">¥{{ product.price }}</span>
                  <el-button
                      type="danger"
                      size="mini"
                      @click="handleBuy(product)"
                      :disabled="product.stock <= 0"
                  >
                    {{ product.stock > 0 ? '立即购买' : '已售罄' }}
                  </el-button>
                </div>
              </div>
            </div>

            <el-empty v-if="products.length === 0" description="暂无商品数据"></el-empty>
          </div>
        </el-scrollbar>
      </div>
    </div>

    <!-- 底部聊天区域 -->
    <div class="live-chat">
      <div class="chat-header">
        <h3>直播聊天室</h3>
        <span>{{ chatMessages.length }}条消息</span>
      </div>
      <el-scrollbar class="chat-messages">
        <div v-for="(msg, index) in chatMessages" :key="index" class="chat-message">
          <div class="message-avatar">
            <el-avatar :size="32" :src="msg.avatar"></el-avatar>
          </div>
          <div class="message-content">
            <div class="message-user">{{ msg.username }}</div>
            <div class="message-text">{{ msg.content }}</div>
          </div>
        </div>
      </el-scrollbar>
      <div class="chat-input">
        <el-input
            v-model="chatInput"
            placeholder="说点什么..."
            @keyup.enter="sendMessage"
        >
          <template #append>
            <el-button icon="el-icon-s-promotion" @click="sendMessage"></el-button>
          </template>
        </el-input>
      </div>
    </div>
  </div>
</template>

<script setup>
import videojs from 'video.js'
import {onMounted, ref, onUnmounted} from "vue";
import { useRoute } from 'vue-router'
import axios from "axios";
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()

const videoPlayer = ref(null)
const player = ref(null)

// 直播详情数据
const liveDetail = ref({
  title: '',
  view_count: '0',
  createTime: '直播未开始',
  streamKey: '' // 添加直播流地址字段
})

// 商品列表
const products = ref([])

// 聊天相关
const chatMessages = ref([])
const chatInput = ref('')

// 获取直播详情
const getLiveDetail = async () => {
  try {
    const response = await axios.get(BASE_URL+'/api/v1/live/room', {params: {id: route.query.id}})
    if (response.data.code == 2000) {
      liveDetail.value = response.data.data
      // 初始化播放器
      initPlayer()
    } else {
      ElMessage.error(response.data.msg)
      // 模拟数据用于开发
      liveDetail.value = {
        title: '农场直播 - 新鲜水果采摘',
        view_count: '1234',
        createTime: '正在直播中',
        streamKey: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8'
      }
      initPlayer()
    }
  } catch (error) {
    ElMessage.error('获取直播详情失败')
    console.error('获取直播详情错误:', error)
    // 模拟数据用于开发
    liveDetail.value = {
      title: '农场直播 - 新鲜水果采摘',
      view_count: '1234',
      createTime: '正在直播中',
      streamKey: 'https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8'
    }
    initPlayer()
  }
}

// 初始化播放器
const initPlayer = () => {
  // 先销毁现有的播放器
  if (player.value) {
    player.value.dispose()
  }

  if (videoPlayer.value && liveDetail.value.streamKey) {
    player.value = videojs(videoPlayer.value, {
      autoplay: true,
      controls: true,
      bigPlayButton: true,
      controlBar: {
        pictureInPictureToggle: false,
        fullscreenToggle: true
      },
      sources: [{
        src: 'http://192.168.92.131:8080/hls/test.m3u8',
        //route.query.streamKey,
        //liveDetail.value.streamKey,
        type: 'application/x-mpegURL'
      }]
    }, () => {
      console.log('播放器加载完成')
    })
  }
}

onMounted(() => {
  getLiveDetail()
  getLiveProducts()
  initChat()
})

// 组件卸载时销毁播放器
onUnmounted(() => {
  if (player.value) {
    player.value.dispose()
  }
})

// 获取直播商品
const getLiveProducts = async () => {
  try {
    const response = await axios.get(BASE_URL+`/api/v1/live/products?id=${route.query.id}`)
    if (response.data.code == 2000) {
      products.value = response.data.data.map(item => ({
        ...item,
        price: parseFloat(item.price).toFixed(2),
        stock: item.stock || 0
      }))
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败')
    console.error('获取商品列表错误:', error)
  }
}

// 刷新商品列表
const refreshProducts = () => {
  getLiveProducts()
  ElMessage.success('商品列表已刷新')
}

// 购买商品
const handleBuy = (product) => {
  if (product.stock <= 0) {
    ElMessage.warning('该商品已售罄')
    return
  }

  ElMessageBox.confirm(`确定要购买 ${product.name} 吗?`, '确认购买', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.post('/api/v1/orders', {
        product_id: product.id,
        quantity: 1,
        room_id: route.query.id
      })

      if (response.data.code === 2000) {
        ElMessage.success('购买成功')
        product.stock -= 1
      } else {
        ElMessage.error(response.data.msg)
      }
    } catch (error) {
      ElMessage.error('购买失败')
      console.error('购买错误:', error)
    }
  }).catch(() => {
    // 用户取消了购买
  })
}

// 初始化聊天室
const initChat = () => {
  // 模拟一些初始消息
  chatMessages.value = [
    { username: '主播', avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png', content: '欢迎大家来到直播间！' },
    { username: '用户1', avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png', content: '主播好！' }
  ]

  // 模拟定时获取新消息
  setInterval(() => {
    if (Math.random() > 0.7) {
      chatMessages.value.push({
        username: '用户' + Math.floor(Math.random() * 10),
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        content: '这个商品不错！'
      })
    }
  }, 5000)
}

// 发送消息
const sendMessage = () => {
  if (!chatInput.value.trim()) return

  chatMessages.value.push({
    username: '我',
    avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
    content: chatInput.value
  })

  chatInput.value = ''
}
</script>

<style scoped>
.live-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.live-content {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

/* 左侧直播区域 */
.live-player-container {
  flex: 1;
  min-width: 0;
}

.video-container {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; /* 16:9 比例 */
  border-radius: 8px;
  overflow: hidden;
  background-color: #000;
}

.video-container video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.live-info {
  margin-top: 15px;
}

.live-title {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.live-meta {
  display: flex;
  gap: 15px;
  color: #666;
  font-size: 14px;
}

.live-meta i {
  margin-right: 5px;
}

/* 右侧商品区域 */
.live-products {
  width: 350px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.products-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.products-scroll {
  height: calc(100vh - 300px);
}

.product-list {
  padding: 0 15px;
}

.product-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 10px;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  margin: 0;
  font-size: 14px;
  color: #333;
  line-height: 1.4;
}

.product-desc {
  margin: 5px 0 0;
  font-size: 12px;
  color: #999;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.product-price {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

/* 底部聊天区域 */
.live-chat {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.chat-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.chat-messages {
  height: 300px;
  padding: 15px;
}

.chat-message {
  display: flex;
  margin-bottom: 15px;
}

.message-avatar {
  margin-right: 10px;
}

.message-content {
  flex: 1;
}

.message-user {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.message-text {
  background: #f5f5f5;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
}

.chat-input {
  padding: 15px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .live-content {
    flex-direction: column;
  }

  .live-products {
    width: 100%;
    margin-top: 20px;
  }
}
</style>